<template>
  <view id="login">
   <view v-if="showInfo">
     <LoginTip :showLogin="showLogin" v-if="showPanel"></LoginTip>
     <view v-if="!showPanel" class="login-panel">
       <view class="cell-title">
         所属单位
       </view>
       <van-cell-group>
         <van-field :value="home" placeholder="请选择所在单位"  clearable data-name="home" @focus="showPop" data-index="2">
         </van-field>
         <uni-popup ref="popup-home" type="bottom">
           <van-picker
               show-toolbar
               :columns="columns"
               data-index="2"
               @cancel="showOrHidePicker"
               @confirm="confirmSelectType"
           />
         </uni-popup>
       </van-cell-group>
       <view class="cell-title">
         电子名片夹
       </view>
       <van-cell-group>
         <van-field :value="folder" placeholder="请选择电子名片夹"  clearable data-name="folder" @focus="showPop" data-index="1">
         </van-field>
         <uni-popup ref="popup" type="bottom">
           <van-picker
               show-toolbar
               :columns="columns1"
               data-index="1"
               @cancel="showOrHidePicker"
               @confirm="confirmSelectType"
           />
         </uni-popup>
       </van-cell-group>
       <button @click="enter" style="margin-top: 20px;" type="primary">进入系统</button>
     </view>
   </view>
    <view v-if="!showInfo" class="login-button">
      <button open-type="getUserInfo" @error="errAuth" @getuserinfo="getUserInfo">授权登录</button>
    </view>
  </view>
</template>

<script>
import {COOKIES, USER_INFO} from "../../store/mutation-types";
import LoginTip from "../../components/loginTip"
import uniPopup from '@/components/uni-popup/uni-popup.vue'
import uniPopupMessage from '@/components/uni-popup/uni-popup-message.vue'
import uniPopupDialog from '@/components/uni-popup/uni-popup-dialog.vue'
import {reqCompanyList, reqFolders, reqLogin} from "../../api/user";

export default {
name: "Login",
  data () {
    return {
      showPanel: true,
      columns: [],
      columns1: [],
      companyList: [],
      folderList: [],
      folder: '',
      home: '',
      showLogin: true,
      showInfo: true,
      code: '',
      company: ''
    }
  },
  methods: {
    showPop (e) {
      const index = e.currentTarget.dataset.index;

      if (index === '1'){
        this.$refs.popup.open()
      } else {
        this.$refs['popup-home'].open()
      }
    },
    async getFolders () {
      const result = await reqFolders({
        companyId: this.companyList.filter(item => item.name === this.home)[0].id
      })
      const { messageBody } = result.data;

      this.folderList = messageBody;
      this.columns1 = messageBody.map(item => item.name);
    },
    async getCompanyList () {
      const result = await reqCompanyList({
        offset: 0,
        limit: 999
      })
      const { list } = result.data.messageBody

      this.companyList = list;
      this.columns = list.map(item => item.name);
    },
    enter () {
      if(!this.home){
        return uni.showToast({
          title: '请选择单位',
          icon: 'none'
        })
      }
      if(!this.folder){
        return uni.showToast({
          title: '请选择电子文件夹',
          icon: 'none'
        })
      }
      uni.login({
        provider: 'weixin',
        success: data1 => {
          reqLogin({
            code: data1.code,
            userInfo: Object.assign({}, this.$store.state.user.userInfo, {
              company: this.companyList.filter(item => item.name === this.home)[0].id,
              folderId: this.folderList.filter(item => item.name === this.folder)[0].id
            })
          }).then(res => {
            const cookies = res['cookies'];

            this.$store.commit(COOKIES, cookies);
            this.$store.commit(USER_INFO, res.data.messageBody);
            setTimeout(() => {
              uni.switchTab({
                url: "/pages/index/index"
              })
            }, 500);
          });
        }
      })
    },
    appLoginWx () {
      // #ifdef MP-WEIXIN
      uni.getSetting({
        success: data => {
         if (data.authSetting['scope.userInfo']){
           this.showInfo = true;
           uni.getProvider({
             service: 'oauth',
             success: res => {
               if (~res.provider.indexOf('weixin')) {
                 uni.login({
                   provider: 'weixin',
                   success:  data => {
                     uni.getUserInfo({
                       provider: 'weixin',
                       success: (info) => {//这里请求接口
                         reqLogin({
                           code: data.code
                         }).then(res => {
                          const resData = res.data;
                          const cookies = res['cookies'];

                          if (!resData.messageBody){
                            this.showPanel = false;
                            this.getCompanyList();
                          } else {
                            console.log(res, 888)
                            this.$store.commit(USER_INFO, resData.messageBody);
                            this.$store.commit(COOKIES, cookies);
                            setTimeout(() => {
                              uni.switchTab({
                                url: "/pages/index/index"
                              })
                            }, 500);
                          }
                         });
                       },
                       fail: () => {
                         this.showLogin = false;
                         uni.showToast({title:"微信登录授权失败", icon:"none"});
                       }
                     })
                   },
                   fail: () => {
                     this.showLogin = false;
                     uni.showToast({title:"微信登录授权失败",icon:"none"});
                   }
                 })
               } else {
                 this.showLogin = false;
                 uni.showToast({
                   title: '请先安装微信或升级版本',
                   icon: "none"
                 });
               }
             }
           });
         } else {
           this.showInfo = false;
         }
        }
      })
      //#endif
    },
    getUserInfo () {
      this.appLoginWx ();
    },
    errAuth (err) {
      console.log(err)
    },
    showOrHidePicker (e) {
      const index = e.currentTarget.dataset.index;

      if (index === '1'){
        this.$refs.popup.close()
      } else {
        this.$refs['popup-home'].close()
      }
    },
    confirmSelectType (e) {
      const { value } = e.detail;
      const index = e.currentTarget.dataset.index;

      if (index === '1'){
        this.folder = value;
        this.$refs.popup.close()
      } else {
        this.home = value;
        this.$refs['popup-home'].close()
        this.getFolders();
      }
    },
  },
  components: {
    LoginTip,
    uniPopup,
    uniPopupMessage,
    uniPopupDialog
  },
  onLoad () {
     this.appLoginWx();
  }
}
</script>

<style lang="less">
.login-panel{
  display: flex;
  flex-direction: column;
  height: 100vh;
  justify-content: center;
}
.cell-title {
  padding: 0.3rem 0.5rem;
  text-align: left;
  font-size: 28rpx;
  color: #828283;
}
.login-button{
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 100vh;
}
</style>